ChatInfo = {
    roomId: null,
    thisUserName: null,
    thatUserName: null
}

//////////////////////////////////////////////////
// 初始化 chatwebsocket
//////////////////////////////////////////////////
let urlChat = 'ws://'+ location.host + '/chat';
let chatwebsocket = new WebSocket(urlChat);

chatwebsocket.onopen = function() {
    console.log("聊天室初始化完成:");
}

chatwebsocket.close = function() {
    console.log("和游戏服务器断开连接!");
}

chatwebsocket.onerror = function() {
    console.log("和服务器的连接出现异常!");
}

window.onbeforeunload = function() {
    chatwebsocket.close();
}

chatwebsocket.onmessage = function(event){
    console.log("[聊天室]"+event.data);
    let resp = JSON.parse(event.data);
    if(!resp.ok){
        alert("连接游戏失败! reason: " + resp.reason);
        // 如果出现连接失败的情况, 回到游戏大厅
        location.replace("/game_hall.html");
        return;
    }
    if(resp.roomId != null && resp.roomId != ''){ //在JavaScript中，null和''（空字符串）是不同的值，它们有不同的用途和含义。
        ChatInfo.roomId = resp.roomId;
    }
    if(resp.thisUserName != null){
        ChatInfo.thisUserName = resp.thisUserName;
    }
    if(resp.thatUserName != null){
        ChatInfo.thatUserName = resp.thatUserName;
    }

    if(resp.sender != null && resp.content != null){
        displayChatMessage(resp.sender, resp.content);
    }
}

//////////////////////////////////////////////////
// 处理聊天室相关操作
//////////////////////////////////////////////////

const messageIn = document.getElementById("messageInput");
messageIn.addEventListener("keydown", function (event) {
    if (event.key === "Enter") {
        event.preventDefault(); // 阻止默认的换行行为
        sendMessage();
    }
});

function displayChatMessage(sender, content) {
    let chatMessages = document.getElementById('chatMessages');
    let messageDiv = document.createElement('div');
    messageDiv.innerHTML = `<strong>${sender}:</strong> ${content}`;
    chatMessages.appendChild(messageDiv);
}

function sendMessage() {
    let messageInput = document.getElementById('messageInput');
    let messageContent = messageInput.value.trim();
    
    if (messageContent !== "") {
        // Send the message to the server
        console.log("send chat ...");
        let request = {
            message: "chat",
            roomId: ChatInfo.roomId,
            sender: ChatInfo.thisUserName,
            content: messageContent,
        };
        chatwebsocket.send(JSON.stringify(request));

        // Clear the input field
        messageInput.value = "";
    }
}